<script setup lang="ts">
import antv from 'ant-design-vue'
import zhCN from 'ant-design-vue/es/locale/zh_CN'
import dayjs from 'dayjs'
import UserLoginModal from '~/components/userLoginModal.vue'
import BaseApp from "~/contentScripts/views/sycm/baseApp.vue";
import Download from '~/contentScripts/views/tao/list/components/download.vue'
import MainImageAnalysis from '~/contentScripts/views/tao/list/components/mainImageAnalysis.vue'
import MarketAnalysis from '~/contentScripts/views/tao/list/components/marketAnalysis.vue'
import TmHotModal from '~/contentScripts/views/tao/list/components/TmHotModal.vue'
import PhoneHotList from '~/contentScripts/views/tao/list/components/TbHotModal.vue'
import User from '~/contentScripts/views/tao/list/components/user.vue'
import '~/styles'
import 'dayjs/locale/zh-cn'
import ListItemBar from '~/contentScripts/views/tao/list/ListItemBar.vue'
import { userInfo } from '~/logic'
import { batch } from '~/logic/apis/taoCategory'
import { setupApp } from '~/logic/common-setup'

dayjs.locale('zh-cn')
const loginVisible = ref(false)
const login = () => {
  loginVisible.value = true
}
onMounted(() => {
  userInfo()
})
const bindBar = ref(true)
const getNewItemData = (selector: string) => {
  return new Promise((resolve, reject) => {
    const key = 'XCSJ_LIST'
    const s = document.createElement('script')
    s.innerHTML = `(function () {let el = document.querySelector('${selector}');if (!el){return;};let key = Object.keys(el).reverse().find(_ => _.startsWith('__reactFiber$')),data = el[key], result = {};data = data.memoizedProps;result = data.children.map(item=>item.props.data);sessionStorage['${key}'] = JSON.stringify(result);})();`
    document.documentElement.appendChild(s)
    setTimeout(() => {
      document.documentElement.removeChild(s)
      const data = sessionStorage.getItem(key)
      resolve(JSON.parse(data == null ? '[]' : data))
      sessionStorage.removeItem(key)
    }
    , 10)
  })
}
const script = document.createElement('script')
script.innerHTML = `(function(){
  var open = window.XMLHttpRequest.prototype.open;
  window.XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
    console.log(url);
    return open.apply(this, arguments);
  };
})()`
document.documentElement.appendChild(script)

const getItemData = () => {
  const dom = document.getElementsByTagName('html')[0].innerHTML
  const regExp = /g_page_config = (.*);/g
  let data = regExp.exec(dom)
  data = JSON.parse(data[1])
  const itemData = data.mods.itemlist.data.auctions
  for (let i = 0; i < itemData.length; i++) {
    itemData[i].item_id = itemData[i].nid
    itemData[i].leafCategory = itemData[i].category
  }
  return itemData
}
const bind = () => {
  setInterval(async () => {
    if (bindBar.value && document.querySelector('.XCSJ-item-bar'))
      return
    bindBar.value = false
    const el = document.querySelector('div[class^=Content--contentInner]')
    if (el) {
      let documentArray = document.querySelectorAll('div[class^=Content--contentInner] > div')
      if (!documentArray.length)
        documentArray = document.querySelectorAll('#mainsrp-itemlist .items .item')

      if (documentArray.length > 0) {
        bindBar.value = true
        const res = await getNewItemData('div[class^=Content--contentInner]')
        const categoryIds = res.map((item: any) => item.leafCategory)
        batch(categoryIds)
        for (let i = 0; i < documentArray.length; i++) {
          const document = documentArray[i]
          const itemData = res[i]
          if (document.querySelector('.XCSJ-item-bar'))
            continue
          const dom = window.document.createElement('div')
          dom.className = 'XCSJ-item-bar'
          const app = createApp({
            render: () => h(ListItemBar, {
              item: itemData,
              // width: document.clientWidth,
              width: 'auto',
            }),
          })
          app.use(antv)
          setupApp(app)
          app.mount(dom)
          document.appendChild(dom)
        }
      }
      else {
        bind()
      }
    }
    else {
      // getItemData()
      const el = document.querySelector('#mainsrp-itemlist .items')
      if (el) {
        let documentArray = document.querySelectorAll('#mainsrp-itemlist .items .item')
        if (!documentArray.length)
          documentArray = document.querySelectorAll('#mainsrp-itemlist .items .item')

        if (documentArray.length > 0) {
          bindBar.value = true
          const res = await getItemData()
          const categoryIds = res.map((item: any) => item.leafCategory)
          batch(categoryIds)
          for (let i = 0; i < documentArray.length; i++) {
            const document = documentArray[i]
            const itemData = res[i]
            if (document.querySelector('.XCSJ-item-bar'))
              continue
            const dom = window.document.createElement('div')
            dom.className = 'XCSJ-item-bar'
            const app = createApp({
              render: () => h(ListItemBar, {
                item: itemData,
                // width: document.clientWidth,
                width: 'auto',
              }),
            })
            app.use(antv)
            setupApp(app)
            app.mount(dom)
            document.appendChild(dom)
          }
        }
        else {
          bind()
        }
      }
    }
  }, 1000)
}

bind()
</script>

<template>
  <base-app :locale="zhCN" prefix-cls="xc-ant">
    <div style="float: right">
      <Logo size="25" style="margin-top: -2px;vertical-align: middle;" />
      <div style="width: 10px;display: inline-block;" />
      <Download @login="login" />
      <MarketAnalysis @login="loginVisible = true" />
      <MainImageAnalysis @login="loginVisible = true" />
      <!--    <CarDiagramAnalysis @login="loginVisible = true" /> -->
<!--      <PhoneHotList @login="loginVisible = true" />-->
<!--      <TmHotModal @login="loginVisible = true" />-->
      <User @login="loginVisible = true" />
    </div>
    <UserLoginModal :login-visible="loginVisible" @close="loginVisible = false" />
  </base-app>
</template>
